import React, { Component } from "react";
import {
    Layout, Menu, Icon, Table, Divider, Button, Modal, Form, Input,
    TimePicker, Popconfirm, message, Alert, DatePicker, Tree, Steps,
    Select, Tabs, List, Card, Collapse, Dropdown, Drawer, Skeleton,
    Transfer, Tag, Col, Row, Avatar, AutoComplete, Empty, notification,
    Progress, Spin, Rate, Upload
} from "antd";
import * as echarts from 'echarts'
import icon from "../img/icon.png";
import { getExistCategoryBySchoolIdAip, getNFCInspectSearchApi, getNFCInspectRecordDetailApi } from "../js/api.js";
import { UrlPrefix, iconFontUrl } from "../js/config.js";

const FormItem = Form.Item;
const Option = Select.Option;
const SubMenu = Menu.SubMenu;
const { Content, Footer, Sider, Header } = Layout;
const { TreeNode } = Tree;
const Step = Steps.Step;
const TabPane = Tabs.TabPane;
const RangePicker = DatePicker.RangePicker;


class nfcinspectRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: false,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            // allCategory: [],
            // allStatus: []
            isSearch: false,
            // existCategory: [],
            searchData: [],
            filteredInfo2: null,
            sortedInfo2: null,
            detailVisible: false,
            detailExist: false,
            searchChartLoading: true,
            chartInspectSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let searchData = [];
        getNFCInspectSearchApi(parseInt(sessionStorage.getItem("departmentId")), undefined)
            .then(res => {
                res.data.forEach((item, index) => {
                    searchData.push({
                        key: index + 1,
                        realname: item.realname,
                        createTime: item.createTime,
                        address: item.address,
                        categoryId: item.categoryId,
                        categoryName: item.category,
                        status: item.status,
                        items: item.item,
                        deviceName: item.deviceName,
                    });
                    //statusData.push(item.statusString);
                });
                this.setState({
                    isSearch: true,
                    searchData: searchData,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.address == undefined && values.deadline == undefined
                && values.status == undefined && values.realname == undefined && values.deviceName == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                // if (values.categoryId !== undefined && values.categoryId.length == 0) {
                //     values.categoryId = undefined;
                // }
                let searchData = [];
                getNFCInspectSearchApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then(res => {
                        res.data.forEach((item, index) => {
                            searchData.push({
                                key: index + 1,
                                realname: item.realname,
                                createTime: item.createTime,
                                address: item.address,
                                categoryId: item.categoryId,
                                categoryName: item.category,
                                status: item.status,
                                items: item.item,
                                deviceName: item.deviceName,
                            });
                            //statusData.push(item.statusString);
                        });
                        this.setState({
                            isSearch: true,
                            searchData: searchData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                    })
            }
        });
    }

    showDetailDrawer(time, items, status) {
        this.setState({
            detailExist: true,
            detailVisible: true,
            currentItems: items,
            currentCreateTime: time,
            currentStatus:status
        })
    }

    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    clearAll2 = () => {
        this.setState({
            filteredInfo2: null,
            sortedInfo2: null,
        });

    }

    handleChange2 = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo2: filters,
            sortedInfo2: sorter,
        });
    }

    handleSearch2 = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     // searchText2: selectedKeys[0],
        // });
    }

    handleSearchReset2 = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     // searchText2: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.refreshData()
        // this.setState({
        //     isSearch: false,
        // })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }


    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let classmatesWidth = undefined;
        let deadlineWidth = undefined;
        let categoryNameWidth = undefined;
        let doneStatusWidth = undefined;
        let actionWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            classmatesWidth = 90;
            deadlineWidth = 120;
            categoryNameWidth = 110;
            doneStatusWidth = 110;
            actionWidth = 110;
        }

        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "巡查员",
            dataIndex: "realname",
            key: "realname",
        },
        {
            title: "排查日期",
            dataIndex: "createTime",
            key: "createTime",
        }, {
            title: '排查点地址',
            dataIndex: 'address',
            key: 'address',
        }, {
            title: '排查设备',
            dataIndex: 'deviceName',
            key: 'deviceName',
        }, {
            title: '排查类别',
            dataIndex: 'categoryName',
            key: 'categoryName',
            width: categoryNameWidth,
        }, {
            title: '完成情况',
            dataIndex: 'doneStatus',
            key: 'doneStatus',
            width: doneStatusWidth,
            render: (text, record) => {
                let normal;
                if (record.status == 0) {
                    normal = (<div></div>)
                } else if (record.status == 3) {
                    normal = (<Tag color={'green'}>一切正常</Tag>)
                } else if (record.status == 4) {
                    normal = (<Tag color={'red'}>有异常</Tag>)
                }
                return (<div><Tag color={'green'}>全部完成</Tag>{normal}</div>)
            },
        }, {
            title: "操作详情",
            key: "action",
            width: actionWidth,
            render: (text, record) => {
                if (record.status == 3 || record.status == 4) {
                    return (
                        <span>
                            <a
                                href="javascript:;"
                                onClick={this.showDetailDrawer.bind(this, record.createTime, record.items, record.status)}>
                                查看详情
                            </a>
                        </span>
                    )
                } else {
                    return (<span>&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;</span>)
                }
            }
        }];

        let categoryOptions;
        // if (this.state.existCategory.length != 0) {
        //     categoryOptions = this.state.existCategory.map((d, index) =>
        //         <Option value={d.id} key={index}>{d.category}</Option>
        //     );
        // }

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="巡查员姓名"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("realname", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡查员姓名"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="筛选日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="排查点地址"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("address", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入排查点地址"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="排查设备"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deviceName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入排查设备"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="完成结果"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("status", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择完成结果">
                                        <Option value="一切正常">一切正常</Option>
                                        <Option value="有异常">有异常</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                <Table
                    dataSource={this.state.searchData}
                    columns={columnsSearch}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />

                {
                    this.state.detailExist ? (
                        <InspectConditionDetail
                            visible={this.state.detailVisible}
                            currentItems={this.state.currentItems}
                            currentCreateTime={this.state.currentCreateTime}
                            currentStatus={this.state.currentStatus}
                            that={this} />
                    ) : null
                }

                {/* <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'每日巡检完成情况展示图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal> */}
            </div>
        )
    }
}

const NFCinspectRecord = Form.create()(nfcinspectRecord);

class InspectConditionDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // currentInspectPlanIds: props.currentInspectPlanIds,
            currentCreateTime: props.currentCreateTime,
            currentItems: props.currentItems,
            currentStatus: props.currentStatus,
            currentStatusArr: props.currentStatusArr,
            currentSinglePlanNormalArr: props.currentSinglePlanNormalArr,
            visible: props.visible,
            that: props.that,
            data: [],
            confirmLoading: false,
            previewVisible: false,
            previewImage: '',
            currentCategory: '',
            currentInspectItem: '',
            currentCategoryPicUrl: '',
            currentCreateUserName: '',
            activeKey: [], //控制list是否可展开
        };
    }

    componentDidMount() {
        this.refreshData(this.state.currentItems, this.state.currentCreateTime);
    }

    componentWillReceiveProps(props) {
        this.setState({
            currentItems: props.currentItems,
            currentCreateTime: props.currentCreateTime,
            currentStatus: props.currentStatus,
            visible: props.visible,
            that: props.that,
        });
        if (props.visible) {
            this.refreshData(props.currentItems, props.currentCreateTime);
        }
    }

    refreshData(currentItems, currentCreateTime) {
        this.setState({
            confirmLoading: true,
        })
        getNFCInspectRecordDetailApi(parseInt(sessionStorage.getItem("departmentId")), currentItems, currentCreateTime)
            .then((res) => {
                console.log(res);
                this.setState({
                    currentCategory: res.data.category,
                    currentNFCItem: res.data.item,
                    currentCreateTime: res.data.createTime,
                    currentCreateUserName: res.data.realname,
                    data: res.data.Info,
                });

                let activeKey = [];
                for (let i = 0; i < res.data.Info.length; i++) {
                    if (res.data.Info[i].status == 4) {
                        activeKey.push(i + '');
                    }
                }
                this.setState({
                    activeKey: activeKey,
                    confirmLoading: false,
                })
            })

    }

    handlePreview = (src) => {
        this.setState({
            previewImage: src,
            previewVisible: true,
        });
    }

    handlePreviewCancel = () => this.setState({ previewVisible: false })


    render() {
        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };

        const panels = this.state.data.map((d, index) => {
            let status;
            if (d.status == 3) {
                status = 3;
            } else if (d.status == 4) {
                status = 4;
            }

            let header = (
                <div style={{ height: '100%', width: '100%' }}>
                    <div style={{ width: '80%', left: 0 }}>
                        {d.content}
                    </div>
                    <img
                        style={{
                            width: '15%',
                            right: 5,
                            top: 0,
                            bottom: 0,
                            margin: 'auto',
                            position: 'absolute',
                        }}
                        alt="计划状态"
                        src={require('../img/status' + status + '.png')}
                    />
                </div>
            );
            let photos;
            let preVideo;
            if (d.photo == '') {
                photos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                photos = d.photoArray.map((d2, index2) =>
                    <Card.Grid
                        key={index2}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt={status == 4 ? '巡检现场照片' : '异常处理照片'}
                            src={UrlPrefix + d2}
                            onClick={this.handlePreview.bind(this, UrlPrefix + d2)} />
                    </Card.Grid>
                );
            }
            preVideo = (
                <Card.Grid
                    key={index}
                    style={gridStyle}>
                    <video
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        src={UrlPrefix + d.video} controls />
                </Card.Grid>
            );

            let question;
            if (d.question == '') {
                question = '无';
            } else {
                question = d.question;
            }

            let listTiele = ['', ''];
            if (status == 4) {
                listTiele[0] = 'NFC巡检记录';
                listTiele[1] = 'NFC巡检照片';
            }
            let listData = [{
                title: listTiele[0],
                description: question,
            }, {
                title: listTiele[1],
                description: (
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                        {photos}
                    </Card>
                ),
            }, {
                title: 'NFC巡检视频',
                description: (
                    d.video == "" ?
                        <span>暂无视频</span>
                        :
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                            {preVideo}
                        </Card>
                )
            }];
            return (
                <Panel header={header} key={index + ''} disabled={(status == 3) ? true : false} >
                    <List
                        itemLayout="horizontal"
                        dataSource={listData}
                        renderItem={item => (
                            <List.Item>
                                <List.Item.Meta
                                    title={item.title}
                                    description={item.description}
                                />
                            </List.Item>
                        )}
                    />
                </Panel>
            );
        })

        let src;
        let alt;
        if (this.state.currentStatus == 3) {
            alt = '全部通过';
            src = 'pass';
        } else if (this.state.currentStatus == 4) {
            alt = '有异常';
            src = 'alert';
        }
        let tab = (
            <div>
              {this.state.currentNFCItem}
              <img
                style={{
                    width: 20,
                    height: 20,
                    marginLeft: 10,
                    marginTop: -3,
                }}
                alt={alt}
                src={require('../img/' + src + '.png')} />
            </div>
        )

        return (
            <div>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={800}
                    title='巡检结果详情'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                    <Tabs>
                        <TabPane
                            tab={tab}
                        >
                            <Skeleton loading={this.state.confirmLoading} active>
                                <Collapse
                                    defaultActiveKey={this.state.activeKey}>
                                    {panels}
                                </Collapse>
                                <Alert
                                    style={{ marginTop: 12 }}
                                    message="提交时间"
                                    description={this.state.currentCreateTime}
                                    type="info"
                                    showIcon
                                />
                            </Skeleton>
                        </TabPane>
                    </Tabs>
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                </Drawer>
                <Modal
                    destroyOnClose
                    visible={this.state.previewVisible}
                    footer={null}
                    bodyStyle={{
                        paddingTop: 48,
                    }}
                    onCancel={this.handlePreviewCancel}>
                    <img
                        alt="照片"
                        style={{ width: '100%' }}
                        src={this.state.previewImage} />
                </Modal>
            </div>

        );
    }
}


export {
    NFCinspectRecord, InspectConditionDetail
}